import { defineStore } from 'pinia'
import storage from 'store'
import router from '@/router'
import UaParser, { IResult as UaResult } from 'ua-parser-js'
import { login, getUserInfo } from '@/mork/user'
import { message } from 'ant-design-vue'

export interface UserState {
  userInfo: UserInfo
  ua: UaResult
  token: string
}

export interface UserInfo {
  id: string
  token: string
  name?: string
  avatar?: string
  roles?: string[]
}
export interface LoginType {
  username: string
  password: string
  remember?: boolean
}

const defaultUserInfo = {
  id: '',
  token: '',
  name: '',
  avatar: '',
  roles: []
}

export const useUserStore = defineStore({
  id: 'PageExample',
  state: (): UserState => ({
    userInfo: { ...defaultUserInfo },
    ua: new UaParser().getResult(),
    token: ''
  }),
  actions: {
    setUserInfo(payload: UserInfo) {
      this.userInfo = payload
      storage.set('USER_ID', payload.id)
    },
    setToken(token: string) {
      this.token = token
      storage.set('ACCESS_TOKEN', token)
    },
    resetUserInfo() {
      this.userInfo = { ...defaultUserInfo }
      storage.clearAll()
    },
    async getUserInfo() {
      const userID = storage.get('USER_ID')
      if (!userID) {
        // 异步调用查询用户信息接口
        getUserInfo(userID).then((res: any) => {
          const { code, data } = res
          if (code == 200) {
            this.setUserInfo(data)
          }
        })
      }
    },
    async login(values: LoginType) {
      // 调用登陆接口
      login(values).then((res: any) => {
        const { code, data, msg } = res
        if (code == 200) {
          this.token = data.token
          storage.set('ACCESS_TOKEN', data.token)
          message.success(msg)
          router.push({ path: '/' })
        } else {
          message.error(msg)
        }
      })
    },
    async logout() {
      // 调用退出登陆接口
      this.resetUserInfo()
      router.push({ name: 'Login' })
    },
    async verification(token: string) {
      // 调用 token 验证接口
      return Promise.resolve(token)
    }
  },
  getters: {
    hasUserInfo(state) {
      return state.userInfo
    }
  }
})
